package dominion.model.actions.base;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import dominion.model.Card;
import dominion.model.GameBoard;
import dominion.model.Player;
import dominion.model.actions.Action;
import dominion.utils.Constants;

public class Library extends Action {

	public Library() {
		cost = 5;
	}

	@Override
	public Card clone() {
		return new Library();
	}

	@Override
	public String toString() {
		return "Library";
	}

	@Override
	public String getDescription() {
		StringBuffer sb = new StringBuffer();
		sb.append(super.getDescription());
		sb.append("Draw until you have 7 cards in hand.\n");
		sb.append("You may set aside any action cards drawn this way, as you draw them.\n");
		sb.append("Discard the set aside cards after you finish drawing.\n");
		return sb.toString();
	}

	@Override
	public void doAction(Player player, GameBoard board, List<Player> players) throws IOException {
		player.changeAction(-1);

		List<Card> tossList = new ArrayList<Card>();
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		String choice = null;
		Constants.printer.print("Type \"keep\" or \"toss\" for every action card drawn.");
		while (player.getHand().size() < 8)
		{
			Card current = player.drawTopCardFromDeck(Constants.LIBRARY_DECK);
			if (current instanceof Action)
			{
				Constants.printer.print("|" + current.toString() + "|");
				while (true)
				{
					choice = in.readLine().trim().toLowerCase();
					if (choice.equals("keep"))
					{
						player.addToDeck(current, Constants.HAND);
						break;
					}
					else if (choice.equals("toss"))
					{
						tossList.add(current);
						break;
					}
					else
					{
						Constants.printer.print("Invalid choice.");
					}
				}
			}
			else
			{
				player.addToDeck(current, Constants.HAND);
			}
		}

		for (Card current : tossList)
		{
			player.addToDeck(current, Constants.DISCARD_DECK);
		}
		playedCard(player);
		Constants.printer.print("New Hand: ");
		Constants.printer.print(player.printHand());
	}
}
